package yanyi.community.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yanyi.community.dto.NotificationDTO;
import yanyi.community.enums.NotificationStatusEnum;
import yanyi.community.enums.NotificationTypeEnum;
import yanyi.community.exception.CustomizeErrorCode;
import yanyi.community.exception.CustomizeException;
import yanyi.community.mapper.NotificationMapper;
import yanyi.community.model.Notification;
import yanyi.community.model.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息通知
 */
@Service
public class NotificationService {
    @Autowired
    private NotificationMapper notificationMapper;

    /**
     * 获取所有回复信息
     */
    public PageInfo list(Long userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("receiver", userId);
        List<Notification> list = notificationMapper.findAll(map);
        if (list.size() == 0) {
            return null;
        }
        PageInfo pi = new PageInfo(list);
        List<NotificationDTO> notificationDTOS = list.stream().map(q -> {
            NotificationDTO dto = new NotificationDTO();
            BeanUtils.copyProperties(q, dto);
            dto.setTypeName(NotificationTypeEnum.nameOfType(q.getType()));
            return dto;
        }).collect(Collectors.toList());

        PageInfo pageInfo = new PageInfo();
        BeanUtils.copyProperties(pi, pageInfo);
        pageInfo.setList(notificationDTOS);
        return pageInfo;
    }

    /**
     * 获取未读信息数量
     */
    public Long unreadCount(Long userId) {
        return notificationMapper.unreadCount(userId);
    }

    /**
     * 阅读消息
     */
    public NotificationDTO read(Long id, User user) {
        Notification notification = notificationMapper.selectByPrimaryKey(id);
        if (notification == null) {
            throw new CustomizeException(CustomizeErrorCode.NOTIFICATION_NOT_FOUND);
        }
        if (!Objects.equals(notification.getReceiver(), user.getId())) {
            throw new CustomizeException(CustomizeErrorCode.READ_NOTIFICATION_FAIL);
        }
        notification.setStatus(NotificationStatusEnum.READ.getStatus());
        notificationMapper.updateByPrimaryKeySelective(notification);
        NotificationDTO notificationDTO = new NotificationDTO();
        BeanUtils.copyProperties(notification, notificationDTO);
        notificationDTO.setTypeName(NotificationTypeEnum.nameOfType(notification.getType()));
        return notificationDTO;
    }
}
